#include "AppInit.h"
#include <QApplication>
#include <QEvent>
#include <QMouseEvent>
#include <QWidget>


AppInit *AppInit::Instance()
{
    /* C++ 之后的静态变量，在多线程环境下，是线程安全的 */
    static AppInit self;
    return &self;
}

AppInit::AppInit(QObject *parent): QObject(parent)
{
}

bool AppInit::eventFilter(QObject *obj, QEvent *evt)
{
    auto *w = (QWidget *)obj;
    if (!w->property("CanMove").toBool())
    {
        return QObject::eventFilter(obj, evt);
    }

    static QPoint mouse_point;
    static bool mouse_pressed = false;

    auto *event = static_cast<QMouseEvent *>(evt);
    if (event->type() == QEvent::MouseButtonPress)
    {
        if (event->button() == Qt::LeftButton)
        {
            mouse_pressed = true;
            mouse_point = event->globalPosition().toPoint() - w->pos();
            return true;
        }
    }
    else if (event->type() == QEvent::MouseButtonRelease)
    {
        mouse_pressed = false;
        return true;
    }
    else if (event->type() == QEvent::MouseMove)
    {
        if (mouse_pressed && (event->buttons() == Qt::LeftButton))
        {
            w->move(event->globalPosition().toPoint() - mouse_point);
            return true;
        }
    }

    return QObject::eventFilter(obj, evt);
}

void AppInit::Start()
{
    QApplication::instance()->installEventFilter(this);
}
